const { Op, literal } = require("sequelize");
const Admin = require("../models/Admin.js");

class AdminService {
    async addAdmin(adminData){
        return Admin.create(adminData);
    }
    async getAdminById(id){
        return Admin.findByPk(id);
    }
    async getAdminByEmail(email){
        return Admin.findOne({
            where: {
                email,
                deleted_at: null
            }
        });
    }
    async getAdminByUsername(username){
        return Admin.findOne({
            where: {
                username,
                deleted_at: null
            }
        });
    }
    async getUserByNameOrEmail(identifier){
        return Admin.findOne({
            where: {
                [Op.or]: [
                    { username: identifier},
                    { email: identifier},
                ]
            }
        });
    }
    async updateAdmin(adminData){
        return Admin.update(adminData, {
            where: {
                id: adminData.id
            }
        });
    }
    async deleteAdmin(adminId){
        return Admin.destroy({
            where: {
                id: adminId
            }
        });
    }
    async getAdminListByPage(page = 1, limit = 10, keyword){
        return Admin.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            where: {
                deleted_at: null,
                [Op.or]: [
                    {
                      username: {
                        [Op.like]: `%${keyword}%`,
                      },
                    },
                    {
                      email: {
                        [Op.like]: `%${keyword}%`,
                      },
                    },
                  ],
            },
            attributes: [
                'id',
                'username',
                'email',
                [literal('DATE_FORMAT(created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
                [literal('DATE_FORMAT(updated_at, "%Y-%m-%d %H:%i:%s")'), 'updated_at'],
                [literal('DATE_FORMAT(deleted_at, "%Y-%m-%d %H:%i:%s")'), 'deleted_at'],
            ]
        });
    }
}

module.exports = new AdminService();